package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"naio/constant"
	"naio/errs"
	"naio/pkg/jwt"
	"strings"
)

// jwt验证中间件
func CheckToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		authorization := c.Request.Header.Get("Authorization")
		if authorization == "" {
			panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, errs.GetMsg(errs.ErrorAuthTokenInvalid)))
		}

		kv := strings.Split(authorization, " ")
		fmt.Printf("kv::%#v", kv)
		if len(kv) != 2 || kv[0] != "Bearer" {
			panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, errs.GetMsg(errs.ErrorAuthTokenInvalid)))
		}

		token := kv[1]
		if !jwt.ValidateToken(token) {
			panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, errs.GetMsg(errs.ErrorAuthTokenInvalid)))
		}
		payload, err := jwt.ParseToken(token)
		if err != nil {
			//token出错
			panic(errs.NewMyAPIError(errs.ErrorAuthTokenInvalid, errs.GetMsg(errs.ErrorAuthTokenInvalid)))
		}

		// 暴露到程序中
		c.Set(constant.ContextKey, payload.Uid)
		c.Set("claims", payload)
		c.Next()
	}
}
